/*
 * Copyright (c) 2009-2013 EvTech Project
 * All rights reserved.
 * 
 * This file is part of Symbol Matching.
 *
 * Symbol Matching is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version.
 *
 * Symbol Matching is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Symbol Matching.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package fi.honkalampisaatio.reaktiopeli.game;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;

import javax.sound.midi.MidiUnavailableException;

import fi.honkalampisaatio.sound.MidiPlayer;

public class MidiSounds {
	private enum STATE{READY, PLAYING, STOPPING};
	private STATE state;
	private int[] c_scale = {60,62,64,65,67,69,71,72};
	private Random rnd = new Random();
	private ArrayList<Integer> playedNotes;
	private MidiPlayer midiPlayer;
	
	public MidiSounds() {
		this.playedNotes = new ArrayList<Integer>();
		this.state = STATE.READY;

		try {
			this.midiPlayer = MidiPlayer.getInstance();
		} catch (MidiUnavailableException e) {
			e.printStackTrace();
			this.midiPlayer = null;
		}	
	}
	
	public void playNotes() {
		if(this.midiPlayer==null) {
			return;
		}
		this.state = STATE.PLAYING;
		Iterator<Integer> it = this.playedNotes.iterator();
		while(it.hasNext() && this.state==STATE.PLAYING) {
			midiPlayer.play(it.next().intValue(), 90);
	        try {
	            Thread.sleep(1000);
	        } catch (InterruptedException e) {
	           e.printStackTrace();
	        }
		}
		this.state = STATE.READY;
	}
	
	public void removeNotes() {
		if(this.state != STATE.READY) {
			this.state = STATE.STOPPING;
		}
		while(this.state != STATE.READY) {
	        try {
	            Thread.sleep(300);
	        } catch (InterruptedException e) {
	           e.printStackTrace();
	        }
		}
		this.playedNotes.clear();
	}

	public Integer playRandomNote() {
		if(this.midiPlayer==null) {
			return null;
		}
		Integer note = new Integer(c_scale[rnd.nextInt(c_scale.length)]);
		midiPlayer.play(note, 90);
		return note;
	}
	
	public void addNote(Integer note) {
		if(note!=null) {
			this.playedNotes.add(note);
		}
	}
	
	public void playWrongPress(){
		if(this.midiPlayer==null) {
			return;
		}
		midiPlayer.playDrum(MidiPlayer.DRUMS.ACOUSTIC_BASS_DRUM.getDrumValue());
	}
	
	public void playRepress(){
		if(this.midiPlayer==null) {
			return;
		}
		midiPlayer.playDrum(MidiPlayer.DRUMS.ACOUSTIC_SNARE.getDrumValue());
	}
	
}
